#课堂练习

import pygame,sys
pygame.init()
screen=pygame.display.set_mode([640,480])
background=pygame.Surface(screen.get_size())
background.fill([255,255,255])
clock=pygame.time.Clock()

class Ball(pygame.sprite.Sprite):
    def __init__(self,image_file,speed,location):
        pygame.sprite.Sprite.__init__(self)
        self.image=pygame.image.load(image_file)
        self.rect=self.image.get_rect()
        self.rect.left,self.rect.top=location
        self.speed=speed

    def move(self):
        if self.rect.left<=screen.get_rect().left or self.rect.right>=screen.get_rect().right:
            self.speed[0]=-self.speed[0]
        newpos=self.rect.move(self.speed)
        self.rect=newpos
    
img='Image\\beach_ball.png'
my_ball=Ball(img,[10,0],[20,20])
#键盘事件参数
delay=100
interval=50
pygame.key.set_repeat(100,50)
#鼠标事件参数
hold_down=False
#定时器事件参数
pygame.time.set_timer(pygame.USEREVENT,1000)
direction=1

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()
        #检测键盘事件
        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_UP:
                my_ball.rect.top=my_ball.rect.top-10
            if event.key==pygame.K_DOWN:
                my_ball.rect.top=my_ball.rect.top+10

        #检测鼠标事件
        if event.type==pygame.MOUSEBUTTONDOWN:
            hold_down=True
        if event.type==pygame.MOUSEBUTTONUP:
            hold_down=False
        if event.type==pygame.MOUSEMOTION:
            if hold_down:
                my_ball.rect.center=event.pos

        #检测定时器事件
        if event.type==pygame.USEREVENT:
            my_ball.rect.centery=my_ball.rect.centery+(30*direction)
            if my_ball.rect.top<=0 or \
                  my_ball.rect.bottom>=screen.get_rect().bottom:
                direction=-direction

    clock.tick(30)
    screen.blit(background,(0,0))
    my_ball.move()
    screen.blit(my_ball.image,my_ball.rect)
    pygame.display.flip()